package com.maxd.modules.antPlant.api;

import com.fasterxml.jackson.databind.JsonNode;
import com.maxd.model.CommonInfo;
import com.maxd.modules.antPlant.api.request.*;
import com.maxd.modules.antPlant.api.resp.*;
import com.maxd.respository.common.CommonRepository;
import com.maxd.utils.Md5Utils;
import feign.Feign;
import feign.Logger;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.slf4j.Slf4jLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mengshx
 * datetime 2024-04-14 09:18
 **/
@Component
public class AntPlanetComplexApi {

    @Autowired
    CommonRepository commonRepository;
    AntPlanetApi api;
    CommonInfo key = new CommonInfo();
    CommonInfo secret = new CommonInfo();


    @PostConstruct
    public void initConfig() {
        key=  commonRepository.findOne(262);
        secret=  commonRepository.findOne(263);
    }

    public AntPlanetComplexApi() {
        api = Feign.builder()
                .decoder(new JacksonDecoder())
                .encoder(new JacksonEncoder())
                .logger(new Slf4jLogger())
                .logLevel(Logger.Level.FULL)
                .target(AntPlanetApi.class, "http://api-gw.haojingke.com");
    }

    public JsonNode activityPage(Pageable page, Integer actid, Integer cid, String keyword) {
        PageActivityListRequest request = new PageActivityListRequest();
        request.setApikey(key.getValue());
        request.setPage(page.getPageNumber());
        request.setLimit(page.getPageSize());
        request.setActid(actid);
        request.setCid(cid);
        request.setKw(keyword);
        return api.activityPage(request);
    }

    public JsonNode activityCategory() {
        PageActivityListRequest request = new PageActivityListRequest();
        request.setApikey(key.getValue());
        request.setPage(1);
        request.setLimit(1000);
        JsonNode jsonNode = api.activityPage(request);
        return jsonNode.get("data").get("cat");
    }

    public JsonNode activityShare(Integer actid, String extentId) {
        ShareActivityRequest request = new ShareActivityRequest();
        request.setApikey(key.getValue());
        request.setActid(actid);
        request.setExtendId(extentId);
        JsonNode jsonNode = api.activityShare(request);
        return jsonNode;
    }

    /**
     * author mengshx
     * 其他订单查询
     * datetime 2024/4/14 16:13 2024/4/14
     *
     * @param pageIndex
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param orderId
     * @return com.fasterxml.jackson.databind.JsonNode
     * @throws
     **/
    public OtherOrderQueryResp queryOtherOrder(Integer pageIndex, Integer pageSize, Date startTime, Date endTime, String orderId) {
        OtherOrderQueryRequest request = new OtherOrderQueryRequest();
        request.setApikey(key.getValue());
        request.setPage(pageIndex);
        request.setLimit(pageSize);
        if (Objects.nonNull(startTime)) {
            request.setStarttime(startTime.getTime()/1000);
        }
        if (Objects.nonNull(endTime)) {
            request.setEndtime(endTime.getTime()/1000);
        }
        request.setOrderid(orderId);
        OtherOrderQueryResp resp = api.queryOtherOrder(request);
        return resp;
    }

    /**
     * author mengshx
     * 充值订单查询
     * datetime 2024/4/14 16:12 2024/4/14
     *
     * @param pageIndex
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param orderId
     * @return com.fasterxml.jackson.databind.JsonNode
     * @throws
     **/
    public RechargeOrderQueryResp queryRechargeOrder(
            Integer pageIndex, Integer pageSize,
            Date startTime, Date endTime,
            String uid,
            String orderId,
            String rechargeno,
            Integer status
    ) {
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("page", pageIndex);
        paramsMap.put("limit", pageSize);
        paramsMap.put("uid", null);
        paramsMap.put("orderid", orderId);
        paramsMap.put("rechargeno", rechargeno);
        if (startTime != null) {
            paramsMap.put("starttime", startTime.getTime() / 1000);
        }
        if (endTime != null) {
            paramsMap.put("endtime", endTime.getTime() / 1000);
        }
        paramsMap.put("status", status);

        //按照自然字符顺序排序
        List<Map.Entry<String, Object>> params = paramsMap.entrySet()
                .stream()
                .filter(entry -> entry.getValue() != null)
                .sorted(Comparator.comparing(Map.Entry::getKey)).collect(Collectors.toList());

        String sign = doSign(buildUrl(params));


        RechargeOrderQueryRequest request = new RechargeOrderQueryRequest();
        request.setApikey(key.getValue());
        request.setSign(sign);

        request.setPage(pageIndex);
        request.setLimit(pageSize);
        request.setUid(uid);
        request.setOrderid(orderId);
        request.setRechargeno(rechargeno);
        if (startTime != null) {
            request.setStarttime(startTime.getTime() / 1000);

        }
        if (endTime != null) {
            request.setEndtime(endTime.getTime() / 1000);
        }
        request.setStatus(status);


        RechargeOrderQueryResp resp = api.queryRechargeOrder(request);

        return resp;
    }

    public MovieOrderQueryResp queryMovieOrder(
            Integer pageIndex, Integer pageSize,
            Date startTime, Date endTime,
            String uid,
            String orderId,
            Integer status
    ) {
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("page", pageIndex);
        paramsMap.put("limit", pageSize);
        paramsMap.put("uid", null);
        paramsMap.put("orderid", orderId);
        if (startTime != null) {
            paramsMap.put("starttime", startTime.getTime() / 1000);
        }
        if (endTime != null) {
            paramsMap.put("endtime", endTime.getTime() / 1000);
        }
        paramsMap.put("status", status);


        String sign = doSign(paramsMap);


        MovieOrderQueryRequest request = new MovieOrderQueryRequest();
        request.setApikey(key.getValue());
        request.setSign(sign);

        request.setPage(pageIndex);
        request.setLimit(pageSize);
        request.setUid(uid);
        request.setOrderid(orderId);
        if (startTime != null) {
            request.setStarttime(startTime.getTime() / 1000);
        }
        if (endTime != null) {
            request.setEndtime(endTime.getTime() / 1000);
        }
        request.setStatus(status);


        MovieOrderQueryResp resp = api.queryMovieOrder(request);

        return resp;
    }

    public FoodOrderQueryResp queryFoodOrder(
            Integer pageIndex, Integer pageSize,
            Date startTime, Date endTime,
            String pf,
            String uid,
            String orderId,
            Integer status
    ) {
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("page", pageIndex);
        paramsMap.put("limit", pageSize);
        paramsMap.put("pf", pf);
        paramsMap.put("uid", null);
        paramsMap.put("orderid", orderId);
        if (startTime != null) {
            paramsMap.put("starttime", startTime.getTime() / 1000);
        }
        if (endTime != null) {
            paramsMap.put("endtime", endTime.getTime() / 1000);
        }
        paramsMap.put("status", status);


        String sign = doSign(paramsMap);


        FoodOrderQueryRequest request = new FoodOrderQueryRequest();
        request.setApikey(key.getValue());
        request.setSign(sign);

        request.setPage(pageIndex);
        request.setLimit(pageSize);
        request.setUid(uid);
        request.setOrderid(orderId);
        if (startTime != null) {
            request.setStarttime(startTime.getTime() / 1000);
        }
        if (endTime != null) {
            request.setEndtime(endTime.getTime() / 1000);
        }
        request.setStatus(status);


        FoodOrderQueryResp resp = api.queryFoodOrder(request);

        return resp;
    }

//    public FoodOrderQueryResp pageWph(
//            Integer pageIndex, Integer pageSize
//    ) {
//
//        return resp;
//    }

    //搜索唯品会
    public WphSearchQueryResp searchWph(
            Integer pageIndex, Integer pageSize,
            String searchKey
    ) {
        WphSearchQueryRequest request = new WphSearchQueryRequest();
        request.setApikey(key.getValue());
        request.setPageindex(pageIndex);
        request.setPagesize(pageSize);
        request.setKeyword(searchKey);
        WphSearchQueryResp resp = api.searchWph(request);
        return resp;
    }

    //转链唯品会
    public WphTransferResp transferWph(
            String relationId,
            String goodsId
    ) {
        WphTransferRequest request = new WphTransferRequest();
        request.setApikey(key.getValue());
        request.setGoodsId(goodsId);
        request.setChanTag(relationId);
        WphTransferResp resp = api.transferWph(request);
        return resp;
    }

    public WphOrderQueryResp queryWphOrder(
            Integer pageIndex, Integer pageSize,
            Date startTime, Date endTime
    ) {


        WphOrderQueryRequest request = new WphOrderQueryRequest();
        request.setApikey(key.getValue());
        request.setPageindex(pageIndex);
        request.setPagesize(pageSize);
        request.setOrderTimeStart(startTime.getTime());
        request.setOrderTimeEnd(endTime.getTime());
        WphOrderQueryResp resp = api.queryWphOrder(request);

        return resp;
    }
    public ZhoubyhOrderQueryResp queryZhoubyhOrder(
            Integer pageIndex, Integer pageSize,
            Date startTime, Date endTime
    ) {
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("page", pageIndex);
        paramsMap.put("limit", pageSize);
        if (startTime != null) {
            paramsMap.put("starttime", startTime.getTime() / 1000);
        }
        if (endTime != null) {
            paramsMap.put("endtime", endTime.getTime() / 1000);
        }


        String sign = doSign(paramsMap);

        ZhoubyhOrderQueryRequest request = new ZhoubyhOrderQueryRequest();
        request.setApikey(key.getValue());
        request.setPage(pageIndex);
        request.setLimit(pageSize);
        request.setStarttime(startTime.getTime()/ 1000);
        request.setEndtime(endTime.getTime()/ 1000);
        request.setSign(sign);
        ZhoubyhOrderQueryResp resp = api.queryZhoubyhOrder(request);
        return resp;
    }


    private String doSign(String url) {
        String wraperSecret = "secret=" + secret.getValue();
        String strsign = wraperSecret + "&" + url + "&" + wraperSecret;
//      String f8677d7b3c86038436855b8484413c22= Md5Utils.md5s("secret=myxqsecret&goods_id=1&rechargeno=13915969891&uid=13915969891&secret=myxqsecret");
        String sign = Md5Utils.md5s(strsign).toLowerCase();
        return sign;
    }

    private String doSign(HashMap<String, Object> paramsMap) {
        List<Map.Entry<String, Object>> params = paramsMap.entrySet()
                .stream()
                .filter(entry -> entry.getValue() != null)
                .sorted(Comparator.comparing(Map.Entry::getKey)).collect(Collectors.toList());

        String sign = doSign(buildUrl(params));
        return sign;
    }

    private String buildUrl(List<Map.Entry<String, Object>> params) {
        StringBuilder urlBuilder = new StringBuilder("");
        for (Map.Entry<String, Object> entry : params) {
            if (entry.getValue() != null) {
                urlBuilder.append(entry.getKey())
                        .append("=")
                        .append(entry.getValue().toString())
                        .append("&");
            }
        }
        // 删除末尾的"&"
        if (urlBuilder.charAt(urlBuilder.length() - 1) == '&') {
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }

        return urlBuilder.toString();
    }

}
